﻿using EightOData.Model;
using System;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using EightOData.Extensions.DialogService;

namespace EightOData
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class GiftEditionPage
    {
        private Uri _imagePath;
        private const String DEFAULT_NAME = "Entrez un nouveau nom";
        private const String DEFAULT_DESCRIPTION = "Donnez la description";
        private const String DEFAULT_QUANTITE = "Donnez la quantité";
        private Gift  _currentGift;

        public GiftEditionPage()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _currentGift = null;

            if (e.Parameter != null && e.Parameter is GiftPage)
            {
                var Gift = e.Parameter as Gift;
                _currentGift = Gift;
                Nom.Text = Gift.Name;

                // Affichage de l'image
                var image = new BitmapImage();
                image.UriSource = Gift.Image;
                Image.Source = image;
            }
        }

        private void Search_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Frame.Navigate(typeof(SearchResultsPage));
        }

        private void BackButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Frame.Navigate(typeof(GiftPage));
        }

        private async void add_image_Click(object sender, RoutedEventArgs e)
        {
            // File picker APIs don't work if the app is in a snapped state.
            // If the app is snapped, try to unsnap it first. Only show the picker if it unsnaps.
            if (Windows.UI.ViewManagement.ApplicationView.Value != Windows.UI.ViewManagement.ApplicationViewState.Snapped ||
                 Windows.UI.ViewManagement.ApplicationView.TryUnsnap() == true)
            {
                Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
                openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;

                // Filter to include a sample subset of file types.
                openPicker.FileTypeFilter.Clear();
                openPicker.FileTypeFilter.Add(".bmp");
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".jpg");

                // Open the file picker.
                Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

                // file is null if user cancels the file picker.
                if (file != null)
                {
                    // Open a stream for the selected file.
                    Windows.Storage.Streams.IRandomAccessStream fileStream =
                        await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    // Set the image source to the selected bitmap.
                    Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                        new Windows.UI.Xaml.Media.Imaging.BitmapImage();

                    bitmapImage.SetSource(fileStream);
                    //displayImage.Source = bitmapImage;
                    this.DataContext = file;

                    using (var stream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        var image = new BitmapImage();
                        await image.SetSourceAsync(stream);
                        Image.Source = image;
                    }


                    // Sauvegarde du chemin
                    var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
                    var copy = await file.CopyAsync(folder, file.Name, NameCollisionOption.GenerateUniqueName);
                    _imagePath = new Uri(copy.Path, UriKind.RelativeOrAbsolute);

                    //mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
                }
            }
        }
        private async void bouton_valider_Click(object sender, RoutedEventArgs e)
        {

            if ((String.IsNullOrWhiteSpace(Nom.Text) || Nom.Text == DEFAULT_NAME) || (String.IsNullOrWhiteSpace(Description.Text) || Description.Text == DEFAULT_DESCRIPTION) || (String.IsNullOrWhiteSpace(Quantite.Text) || Quantite.Text == DEFAULT_QUANTITE))
            {
                await(new MessageDialog("Le formulaire n'a pas été correctement rempli !")).ShowAsync();
            }
            else if (_currentGift == null)
            {
                Gift newGift = new Gift  {
                        Name = Nom.Text,
                        Description = Description.Text,
                        Quantity= Quantite.Text,
                        Image = _imagePath
                    };

                // Si le contenu du formulaire est valide, création de la liste de cadeaux
                Frame.Navigate(typeof(GiftPage), newGift);


                Save(newGift);
            }
            else
            {
                // Si le contenu du formulaire est valide, EDITION du cadeau
                // TODO : Modifier les propriétés du cadeau existant
                _currentGift.Name = Nom.Text;
                _currentGift.Description = Description.Text;
                _currentGift.Quantity = Quantite.Text;
                _currentGift.Image = _imagePath;
                Frame.Navigate(typeof(GiftPage));
                Save(_currentGift);
            }
        }
    }
}
